import base64
import os
import random
import time
from io import BytesIO

import requests
from PIL.Image import Image
from fake_useragent import UserAgent
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import ddddocr

# 启动浏览器命令
# start D:/Code/Python/flask-project/chrome-win/chrome.exe --remote-debugging-port=13888

# 实例化 UserAgent 类
ua = UserAgent()

# 当前文件所在的文件夹路径
current_path = os.path.abspath(os.path.dirname(__file__))
# chrome浏览器路径
chrome_location = os.path.join(current_path, 'chrome-win')
# chrome.exe完整路径
browser_location = os.path.join(chrome_location, 'chrome.exe')
# chromedriver.exe的完整路径
driver_location = os.path.join(chrome_location, 'chromedriver.exe')
# 创建一个Servic对象，传入ChromeDriver的路径
service = Service(driver_location)
# 创建Chrome选项
options = Options()
# options.binary_location = browser_location
# # 不显示 Chrom正受到自动测试软件控制
# options.add_experimental_option("excludeSwitches", ['enable-automation'])
# 禁用自动化控制特性，避免被网站检测到
# window.navigator.webdriver属性设置为: false
# options.add_argument("--disable-blink-features=AutomationControlled")
# 无头模式
options.add_argument("--headless")
options.add_argument(f'User-Agent={ua.random}')
# options.add_argument(f'--user-agent={ua.random}')
# 关闭webrtc
# preferences = {
#     "webrtc.ip_handling_policy": "disable_non_proxied_udp",
#     "webrtc.multiple_routes_enabled": False,
#     "webrtc.nonproxied_udp_enabled": False
# }
# options.add_experimental_option("prefs", preferences)
options.add_argument('--start-maximized')
# options.add_argument('--remote-debugging-port=13888')

options.add_experimental_option("debuggerAddress", "127.0.0.1:13888")

driver = webdriver.Chrome(service=service, options=options)
# driver = webdriver.Remote(command_executor="http://127.0.0.1:13888",options=options)
# driver = webdriver.Chrome(options=options)
det = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)
wait = WebDriverWait(driver, 20, poll_frequency=0.5)

# 判断验证码是否存在,是否需要验证
def is_required_verify():
    result = False
    try:
        iframe_xpath ='//*[@id="captcha-iframe"]'
        wait_result = wait.until(lambda x: x.find_elements(By.XPATH, iframe_xpath).__len__() > 0)
        iframe_element = driver.find_element(By.XPATH, iframe_xpath)
        driver.switch_to.frame(iframe_element)
        tips_xpath = '//*[@id="bg-img"]'
        result = wait.until(lambda x: x.find_elements(By.XPATH, tips_xpath).__len__() > 0)

    except Exception as e:
        print(e)
    finally:
        return result


def base64_to_image(base64_str,save_path):
    head, content = base64_str.split(',')
    # 输入为base64格式字符串，输出为PIL格式图片
    byte_data = base64.b64decode(content)  # base64转二进制
    with open(save_path, 'wb') as f:
        f.write(byte_data)


# def get_track(distance):      # distance为传入的总距离
#     # 移动轨迹
#     track=[]
#     # 当前位移
#     current=0
#     # 减速阈值
#     mid=distance*4/5
#     # 计算间隔
#     t=0.2
#     # 初速度
#     v=0
#
#     while current<distance:
#         if current<mid:
#             # 加速度为2
#             a=2
#         else:
#             # 加速度为-2
#             a=-3
#         v0=v
#         # 当前速度
#         v=v0+a*t
#         # 移动距离
#         move=v0*t+1/2*a*t*t
#         # 当前位移
#         current+=move
#         # 加入轨迹
#         track.append(round(move))
#     return track
def get_track(distance):      # distance为传入的总距离
    # 移动轨迹
    track=[]
    track.append(distance-6)
    track.append(6)
    return track
def move_to_gap(slider,tracks):     # slider是要移动的滑块,tracks是要传入的移动轨迹
    ActionChains(driver).click_and_hold(slider).perform()
    for x in tracks:
        time.sleep(0.6)
        y= random.randint(2,3)
        ActionChains(driver).move_by_offset(xoffset=x,yoffset=y).perform()
    time.sleep(0.5)
    ActionChains(driver).release().perform()



# 滑块
def verify():
    # 验证码元素的xpath
    background_xpath='//*[@id="bg-img"]'
    single_slider_xpath='//div[@class="bg-img-div"][1]'
    try:
        # 判断文件夹是否存在，若不存在则创建
        img_dir = os.path.join(current_path, "img")
        # 判断文件夹是否存在，若不存在则创建
        if not os.path.exists(img_dir):
            os.makedirs(img_dir)
        wait_result = wait.until(lambda x: x.find_element(By.XPATH, background_xpath)
                                 .get_attribute('src').__len__() > 0)
        single_slider_ele = driver.find_element(By.XPATH, single_slider_xpath)
        full_img_path=os.path.join(current_path, "img", "single_slider.jpg")
        single_slider_ele.screenshot(full_img_path)
        with open(full_img_path, 'rb') as f:
            base64_str = base64.b64encode(f.read()).decode()  ## 图片二进制流base64字符串
        # 云码
        url = "http://api.jfbym.com/api/YmServer/customApi"
        data = {
            ## 关于参数,一般来说有3个;不同类型id可能有不同的参数个数和参数名,找客服获取
            "token": "aaaaaaaaaaa",
            "type": "22222",
            "image": base64_str,
        }
        _headers = {
            "Content-Type": "application/json"
        }
        with requests.request("POST", url, headers=_headers, json=data)  as response:
            resp_data=response.json()
            print(resp_data)
            if resp_data["code"] == 10000:
                distance=int(resp_data["data"]["data"])
                slider_button = driver.find_element(By.XPATH, '//*[@id="slider-move-btn"]')
                print(f"滑块按钮位置：{slider_button.location}")
                # 计算滑块轨迹
                tracks = get_track(distance)
                # 移动滑块
                move_to_gap(slider_button, tracks)
                try:
                    wait_content = WebDriverWait(driver, 5, poll_frequency=1)
                    content_result= wait_content.until(lambda x: x.find_element(By.XPATH, '//*[@id="kz002001001"]'))
                except Exception as e:
                   print(e)
    except Exception as e:
        print(e)


# 点击查询
def click_select():
    # 点击查询
    click_xpath = '//button[@class="el-button el-button--primary el-button--medium"]/span'
    click_ele = driver.find_element(By.XPATH, click_xpath)
    driver.execute_script("arguments[0].click()", click_ele)


if __name__ == '__main__':
    try:
        # url = "https://www.etrading.cn/captcha/c?url=https://www.etrading.cn/noticeDetails_jyxx.html?infoid=f063503f-d425-4c0c-85a2-fbe57d244a26&categorynum=002001001&title=%E5%A6%82%E7%9A%8B%E5%B8%82%E9%95%BF%E6%B1%9F%E9%95%87%E5%AE%9C%E5%B1%85%E5%AE%9C%E4%B8%9A%E5%92%8C%E7%BE%8E%E4%B9%A1%E6%9D%91%E5%BB%BA%E8%AE%BE%E9%A1%B9%E7%9B%AE(%E6%9D%A8%E6%B4%B2%E7%A4%BE%E5%8C%BA)?"
        # url="https://baijiahao.baidu.com/s?id=1816228266652249286"
        url="https://www.ccgp-gansu.gov.cn/web/article/8aeeb5df93241991019347503d933724.html"
        driver.get(url)
        driver.quit()
        # 是否需要验证
        with open(os.path.join(current_path,"js","Cursor.js"),'r',encoding="utf-8") as f:
            mouse_js=f.read()
            driver.execute_script(mouse_js)
        iframe_xpath = '//*[@id="captcha-iframe"]'
        wait_result = wait.until(lambda x: x.find_elements(By.XPATH, iframe_xpath).__len__() > 0)
        iframe_element = driver.find_element(By.XPATH, iframe_xpath)
        driver.switch_to.frame(iframe_element)
        for i in range(3):
            ele_list=driver.find_elements(By.XPATH, '//*[@id="kz002001001"]')
            if ele_list.__len__()==0:
                verify()
    except Exception as e:
        print(e)
    finally:
        wait_result=driver.find_element(By.XPATH, '//*[@id="kz002001001"]').text
        print(wait_result)
        driver.quit()
